package hong.jun.filter;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String jsonToken = request.getHeader("json-token");
        if (StringUtils.hasLength(jsonToken)) {
            //获取到请求头中的json

            //认证信息，授权信息
            JSONObject jsonObject = JSON.parseObject(jsonToken);

            //用户名
            String username = jsonObject.getString("username");
            //权限
            JSONArray userAuthorities = jsonObject.getJSONArray("userauthorities");

            //把权限转换成转换成数组
            String[] auths = new String[userAuthorities.size()];
            String[] authorities = userAuthorities.toArray(auths);

            //把用户信息和权限封装成 UsernamePasswordAuthenticationToken
            UsernamePasswordAuthenticationToken token =
                    new UsernamePasswordAuthenticationToken(username, null, AuthorityUtils.createAuthorityList(authorities));

            //设置detail,根据请求对象创建一个detail
            token.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            //把UsernamePasswordAuthenticationToken填充到security上下文
            SecurityContextHolder.getContext().setAuthentication(token);

        }
        //放行
        filterChain.doFilter(request, response);
    }
}
